<template>
  <div class="usage-statistics">
    <div class="page-header">
      <h1>使用统计分析</h1>
      <p>分析平台用户行为和系统使用情况</p>
      <div class="header-actions">
        <el-button type="primary" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 核心指标 -->
    <div class="key-metrics">
      <div class="metric-card">
        <div class="metric-header">
          <h3>👥 用户统计</h3>
          <span class="metric-trend positive">+{{ metrics.userGrowth }}%</span>
        </div>
        <div class="metric-body">
          <div class="metric-value">{{ formatNumber(metrics.totalUsers) }}</div>
          <div class="metric-label">总用户数</div>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h3>🔍 检测统计</h3>
          <span class="metric-trend positive">+{{ metrics.detectionGrowth }}%</span>
        </div>
        <div class="metric-body">
          <div class="metric-value">{{ formatNumber(metrics.totalDetections) }}</div>
          <div class="metric-label">总检测次数</div>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h3>⚡ 活跃用户</h3>
          <span class="metric-trend positive">+{{ metrics.activeUserGrowth }}%</span>
        </div>
        <div class="metric-body">
          <div class="metric-value">{{ formatNumber(metrics.activeUsers) }}</div>
          <div class="metric-label">日活跃用户</div>
        </div>
      </div>

      <div class="metric-card">
        <div class="metric-header">
          <h3>✅ 准确率</h3>
          <span class="metric-trend positive">+{{ metrics.accuracyImprovement }}%</span>
        </div>
        <div class="metric-body">
          <div class="metric-value">{{ metrics.accuracy }}%</div>
          <div class="metric-label">平均准确率</div>
        </div>
      </div>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <!-- 用户增长趋势 -->
      <div class="chart-card">
        <h3>📈 用户增长趋势</h3>
        <div class="chart-container">
          <div ref="userGrowthChart" class="chart"></div>
        </div>
      </div>

      <!-- 检测类型分布 -->
      <div class="chart-card">
        <h3>🔍 检测类型分布</h3>
        <div class="chart-container">
          <div ref="detectionTypesChart" class="chart"></div>
        </div>
      </div>

      <!-- 活跃时间分布 -->
      <div class="chart-card">
        <h3>⏰ 活跃时间分布</h3>
        <div class="chart-container">
          <div ref="activeTimeChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 地区分布 - 独占一行 -->
    <div class="region-chart-section">
      <div class="chart-card region-chart-card">
        <h3>🌍 地区分布</h3>
        <div class="chart-container region-chart-container">
          <div ref="regionChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 详细统计表 -->
    <div class="detailed-stats">
      <div class="stats-table">
        <h3>📊 详细统计数据</h3>
        <div class="table-container">
          <el-table :data="detailedStats" stripe style="width: 100%">
            <el-table-column prop="date" label="时间" width="120" />
            <el-table-column prop="newUsers" label="新增用户" width="120">
              <template #default="scope">
                {{ scope.row.newUsers.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="activeUsers" label="活跃用户" width="120">
              <template #default="scope">
                {{ scope.row.activeUsers.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="detections" label="检测次数" width="120">
              <template #default="scope">
                {{ scope.row.detections.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="accuracy" label="准确率" width="100">
              <template #default="scope">
                {{ scope.row.accuracy }}%
              </template>
            </el-table-column>
            <el-table-column prop="responseTime" label="响应时间" width="120">
              <template #default="scope">
                {{ scope.row.responseTime }}ms
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 功能使用排行 -->
      <div class="feature-ranking">
        <h3>🏆 功能使用排行</h3>
        <div class="ranking-list">
          <div class="ranking-item" v-for="(feature, index) in featureRanking" :key="index">
            <div class="ranking-number">{{ index + 1 }}</div>
            <div class="ranking-info">
              <div class="feature-name">{{ feature.name }}</div>
              <div class="feature-usage">{{ feature.usage.toLocaleString() }} 次使用</div>
            </div>
            <div class="ranking-percent">{{ feature.percentage }}%</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import chinaGeoJson from '@/assets/100000_full.json'
// 图表引用
const userGrowthChart = ref(null)
const detectionTypesChart = ref(null)
const activeTimeChart = ref(null)
const regionChart = ref(null)

// 图表实例
let userGrowthChartInstance = null
let detectionTypesChartInstance = null
let activeTimeChartInstance = null
let regionChartInstance = null

// 核心指标
const metrics = reactive({
  totalUsers: 128456,
  userGrowth: 12.5,
  totalDetections: 2856734,
  detectionGrowth: 8.3,
  activeUsers: 45678,
  activeUserGrowth: 15.2,
  accuracy: 94.7,
  accuracyImprovement: 2.1
})

// 详细统计数据
const detailedStats = ref([
  { date: '2024-01-15', newUsers: 1234, activeUsers: 45678, detections: 156789, accuracy: 94.7, responseTime: 245 },
  { date: '2024-01-14', newUsers: 1156, activeUsers: 44532, detections: 152456, accuracy: 94.5, responseTime: 238 },
  { date: '2024-01-13', newUsers: 1287, activeUsers: 46123, detections: 158234, accuracy: 94.8, responseTime: 252 },
  { date: '2024-01-12', newUsers: 1345, activeUsers: 47234, detections: 162345, accuracy: 94.6, responseTime: 241 },
  { date: '2024-01-11', newUsers: 1198, activeUsers: 45234, detections: 154567, accuracy: 94.9, responseTime: 236 },
  { date: '2024-01-10', newUsers: 1456, activeUsers: 48567, detections: 165432, accuracy: 95.1, responseTime: 229 },
  { date: '2024-01-09', newUsers: 1234, activeUsers: 46789, detections: 157890, accuracy: 94.3, responseTime: 258 }
])

// 功能使用排行
const featureRanking = ref([
  { name: '文本谣言检测', usage: 1234567, percentage: 45.2 },
  { name: '图像真伪识别', usage: 823456, percentage: 30.1 },
  { name: '反诈骗预警', usage: 456789, percentage: 16.7 },
  { name: 'AI内容检测', usage: 234567, percentage: 8.6 },
  { name: '声纹识别', usage: 123456, percentage: 4.5 },
  { name: '综合分析', usage: 89234, percentage: 3.3 }
])

// 中国各省用户分布数据 - 确保省份名称与地图匹配
const chinaRegionData = ref([
  { name: '北京市', value: 15420 },
  { name: '天津市', value: 6580 },
  { name: '河北省', value: 18950 },
  { name: '山西省', value: 9320 },
  { name: '内蒙古自治区', value: 7180 },
  { name: '辽宁省', value: 12580 },
  { name: '吉林省', value: 8760 },
  { name: '黑龙江省', value: 9420 },
  { name: '上海市', value: 22350 },
  { name: '江苏省', value: 28740 },
  { name: '浙江省', value: 24680 },
  { name: '安徽省', value: 15290 },
  { name: '福建省', value: 13850 },
  { name: '江西省', value: 11470 },
  { name: '山东省', value: 25630 },
  { name: '河南省', value: 22140 },
  { name: '湖北省', value: 16920 },
  { name: '湖南省', value: 18370 },
  { name: '广东省', value: 35280 },
  { name: '广西壮族自治区', value: 12840 },
  { name: '海南省', value: 4680 },
  { name: '重庆市', value: 9750 },
  { name: '四川省', value: 20560 },
  { name: '贵州省', value: 8930 },
  { name: '云南省', value: 11840 },
  { name: '西藏自治区', value: 1520 },
  { name: '陕西省', value: 13280 },
  { name: '甘肃省', value: 7340 },
  { name: '青海省', value: 2180 },
  { name: '宁夏回族自治区', value: 3750 },
  { name: '新疆维吾尔自治区', value: 6920 },
  { name: '台湾省', value: 8640 },
  { name: '香港特别行政区', value: 5230 },
  { name: '澳门特别行政区', value: 1890 },
  // 添加不带省市后缀的备用名称
  { name: '北京', value: 15420 },
  { name: '天津', value: 6580 },
  { name: '河北', value: 18950 },
  { name: '山西', value: 9320 },
  { name: '内蒙古', value: 7180 },
  { name: '辽宁', value: 12580 },
  { name: '吉林', value: 8760 },
  { name: '黑龙江', value: 9420 },
  { name: '上海', value: 22350 },
  { name: '江苏', value: 28740 },
  { name: '浙江', value: 24680 },
  { name: '安徽', value: 15290 },
  { name: '福建', value: 13850 },
  { name: '江西', value: 11470 },
  { name: '山东', value: 25630 },
  { name: '河南', value: 22140 },
  { name: '湖北', value: 16920 },
  { name: '湖南', value: 18370 },
  { name: '广东', value: 35280 },
  { name: '广西', value: 12840 },
  { name: '海南', value: 4680 },
  { name: '重庆', value: 9750 },
  { name: '四川', value: 20560 },
  { name: '贵州', value: 8930 },
  { name: '云南', value: 11840 },
  { name: '西藏', value: 1520 },
  { name: '陕西', value: 13280 },
  { name: '甘肃', value: 7340 },
  { name: '青海', value: 2180 },
  { name: '宁夏', value: 3750 },
  { name: '新疆', value: 6920 },
  { name: '台湾', value: 8640 },
  { name: '香港', value: 5230 },
  { name: '澳门', value: 1890 }
])

// 方法
const formatNumber = (number) => {
  if (number >= 1000000) {
    return (number / 1000000).toFixed(1) + 'M'
  } else if (number >= 1000) {
    return (number / 1000).toFixed(1) + 'K'
  }
  return number.toString()
}

const refreshData = async () => {
  try {
    // 模拟数据刷新
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新指标
    metrics.totalUsers += Math.floor(Math.random() * 100)
    metrics.activeUsers += Math.floor(Math.random() * 50)
    metrics.totalDetections += Math.floor(Math.random() * 1000)
    
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

const exportData = async () => {
  try {
    // 模拟数据导出
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('数据导出成功')
  } catch (error) {
    ElMessage.error('数据导出失败')
  }
}

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return
  
  userGrowthChartInstance = echarts.init(userGrowthChart.value)
  
  const option = {
    title: {
      text: '用户增长趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['新增用户', '活跃用户'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: [2300, 2800, 3200, 3500, 4200, 4800, 5200, 5800, 6200, 6800, 7200, 7600],
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '活跃用户',
        type: 'line',
        data: [15000, 18000, 21000, 24000, 28000, 32000, 35000, 38000, 42000, 45000, 48000, 52000],
        smooth: true,
        itemStyle: { color: '#91cc75' }
      }
    ]
  }
  
  userGrowthChartInstance.setOption(option)
}

// 初始化检测类型分布图表
const initDetectionTypesChart = () => {
  if (!detectionTypesChart.value) return
  
  detectionTypesChartInstance = echarts.init(detectionTypesChart.value)
  
  const option = {
    title: {
      text: '检测类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '检测类型',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 45, name: '文本检测' },
          { value: 30, name: '图像检测' },
          { value: 15, name: '音频检测' },
          { value: 10, name: '视频检测' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  detectionTypesChartInstance.setOption(option)
}

// 初始化活跃时间分布图表
const initActiveTimeChart = () => {
  if (!activeTimeChart.value) return
  
  activeTimeChartInstance = echarts.init(activeTimeChart.value)
  
  const option = {
    title: {
      text: '24小时活跃用户分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: Array.from({ length: 24 }, (_, i) => `${i}:00`)
    },
    yAxis: {
      type: 'value',
      name: '活跃用户数'
    },
    series: [
      {
        name: '活跃用户',
        type: 'line',
        data: [1200, 800, 600, 400, 300, 500, 800, 1500, 2200, 2800, 3200, 3500, 3800, 4200, 4500, 4800, 5200, 5800, 6200, 5500, 4800, 3800, 2800, 1800],
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(84, 112, 198, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(84, 112, 198, 0.1)'
            }
          ])
        },
        itemStyle: { color: '#5470c6' }
      }
    ]
  }
  
  activeTimeChartInstance.setOption(option)
}

// 初始化地区分布图表
const initRegionChart = async () => {
  if (!regionChart.value) return
  
  try {
    // 从CDN加载中国地图数据
    const chinaMapData = chinaGeoJson
    
    // 注册中国地图
    echarts.registerMap('china', chinaMapData)
    
    regionChartInstance = echarts.init(regionChart.value)
    
    // 获取数据的最大值和最小值，用于设置颜色范围
    const values = chinaRegionData.value.map(item => item.value)
    const maxValue = Math.max(...values)
    const minValue = Math.min(...values)
    
    const option = {
      title: {
        text: '🌍 用户地区分布',
        left: 'center',
        textStyle: {
          fontSize: 20,
          color: '#333',
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          if (params.value) {
            return `${params.name}<br/>用户数量：${params.value.toLocaleString()}人<br/>占比：${((params.value / chinaRegionData.value.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(2)}%`
          }
          return `${params.name}<br/>暂无数据`
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ccc',
        borderWidth: 1,
        textStyle: {
          color: '#333'
        },
        extraCssText: 'box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);'
      },
      visualMap: {
        min: minValue,
        max: maxValue,
        left: 'left',
        top: 'bottom',
        text: [`高（${maxValue.toLocaleString()}）`, `低（${minValue.toLocaleString()}）`],
        textStyle: {
          color: '#333',
          fontSize: 12
        },
        calculable: true,
        orient: 'horizontal',
        itemWidth: 20,
        itemHeight: 140,
        inRange: {
          // 使用从浅到深的蓝色渐变，用户数量多的省份颜色更深
          color: [
            '#f0f9ff',  // 最浅 - 用户数量最少
            '#e0f2fe',  
            '#bae6fd',  
            '#7dd3fc',  
            '#38bdf8',  
            '#0ea5e9',  
            '#0284c7',  
            '#0369a1',  
            '#075985',  
            '#0c4a6e'   // 最深 - 用户数量最多
          ]
        },
        outOfRange: {
          color: '#f5f5f5'
        },
        formatter: function(value) {
          return value.toLocaleString() + '人'
        }
      },
      series: [
        {
          name: '用户分布',
          type: 'map',
          map: 'china',
          roam: true,
          scaleLimit: {
            min: 1.0,
            max: 5
          },
          zoom: 1.1,
          itemStyle: {
            areaColor: '#f0f9ff',
            borderColor: '#ffffff',
            borderWidth: 1.5,
            shadowColor: 'rgba(0, 0, 0, 0.1)',
            shadowOffsetX: 1,
            shadowOffsetY: 1
          },
          emphasis: {
            itemStyle: {
              areaColor: '#ff6b6b',
              borderColor: '#ffffff',
              borderWidth: 2,
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              shadowBlur: 20,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              show: true,
              fontSize: 12,
              fontWeight: 'bold',
              color: '#fff'
            }
          },
          select: {
            itemStyle: {
              areaColor: '#ffa500'
            }
          },
          label: {
            show: true,
            fontSize: 8,
            color: '#333333',
            fontWeight: 'normal'
          },
          data: chinaRegionData.value
        }
      ]
    }
    
    regionChartInstance.setOption(option)
    
    // 添加点击事件
    regionChartInstance.on('click', function(params) {
      console.log('点击了省份：', params.name, '用户数量：', params.value)
      ElMessage.info(`${params.name}：${params.value ? params.value.toLocaleString() : '暂无数据'}人`)
    })
    
  } catch (error) {
    console.error('加载地图数据失败:', error)
    ElMessage.error('加载地图数据失败，请检查网络连接')
    
    // 如果网络加载失败，使用备用的简化版本
    initRegionChartFallback()
  }
}

// 备用的简化版本地图初始化
const initRegionChartFallback = () => {
  if (!regionChart.value) return
  
  // 使用简化的中国地图数据
  const fallbackMapData = {
    type: "FeatureCollection",
    features: [
      {
        type: "Feature",
        properties: { name: "广东" },
        geometry: {
          type: "Polygon",
          coordinates: [[[109.61, 20.26], [116.97, 20.26], [116.97, 25.51], [109.61, 25.51], [109.61, 20.26]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "江苏" },
        geometry: {
          type: "Polygon",
          coordinates: [[[116.36, 30.45], [121.95, 30.45], [121.95, 35.20], [116.36, 35.20], [116.36, 30.45]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "山东" },
        geometry: {
          type: "Polygon",
          coordinates: [[[114.48, 34.28], [122.72, 34.28], [122.72, 38.40], [114.48, 38.40], [114.48, 34.28]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "浙江" },
        geometry: {
          type: "Polygon",
          coordinates: [[[118.01, 27.02], [123.24, 27.02], [123.24, 31.11], [118.01, 31.11], [118.01, 27.02]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "河南" },
        geometry: {
          type: "Polygon",
          coordinates: [[[110.21, 31.38], [116.61, 31.38], [116.61, 36.22], [110.21, 36.22], [110.21, 31.38]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "四川" },
        geometry: {
          type: "Polygon",
          coordinates: [[[97.35, 26.05], [108.54, 26.05], [108.54, 34.32], [97.35, 34.32], [97.35, 26.05]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "湖北" },
        geometry: {
          type: "Polygon",
          coordinates: [[[108.50, 29.05], [116.07, 29.05], [116.07, 33.20], [108.50, 33.20], [108.50, 29.05]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "湖南" },
        geometry: {
          type: "Polygon",
          coordinates: [[[108.79, 24.64], [114.25, 24.64], [114.25, 30.08], [108.79, 30.08], [108.79, 24.64]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "河北" },
        geometry: {
          type: "Polygon",
          coordinates: [[[113.27, 36.05], [119.69, 36.05], [119.69, 42.61], [113.27, 42.61], [113.27, 36.05]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "安徽" },
        geometry: {
          type: "Polygon",
          coordinates: [[[114.89, 29.41], [119.32, 29.41], [119.32, 34.66], [114.89, 34.66], [114.89, 29.41]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "江西" },
        geometry: {
          type: "Polygon",
          coordinates: [[[113.57, 24.29], [118.47, 24.29], [118.47, 30.05], [113.57, 30.05], [113.57, 24.29]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "福建" },
        geometry: {
          type: "Polygon",
          coordinates: [[[115.84, 23.33], [120.44, 23.33], [120.44, 28.20], [115.84, 28.20], [115.84, 23.33]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "广西" },
        geometry: {
          type: "Polygon",
          coordinates: [[[104.26, 20.54], [112.04, 20.54], [112.04, 26.24], [104.26, 26.24], [104.26, 20.54]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "云南" },
        geometry: {
          type: "Polygon",
          coordinates: [[[97.31, 21.14], [106.20, 21.14], [106.20, 29.15], [97.31, 29.15], [97.31, 21.14]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "贵州" },
        geometry: {
          type: "Polygon",
          coordinates: [[[103.59, 24.37], [109.56, 24.37], [109.56, 29.13], [103.59, 29.13], [103.59, 24.37]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "重庆" },
        geometry: {
          type: "Polygon",
          coordinates: [[[105.29, 28.16], [110.11, 28.16], [110.11, 32.20], [105.29, 32.20], [105.29, 28.16]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "陕西" },
        geometry: {
          type: "Polygon",
          coordinates: [[[105.29, 31.42], [111.15, 31.42], [111.15, 39.35], [105.29, 39.35], [105.29, 31.42]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "山西" },
        geometry: {
          type: "Polygon",
          coordinates: [[[110.14, 34.34], [114.33, 34.34], [114.33, 40.44], [110.14, 40.44], [110.14, 34.34]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "甘肃" },
        geometry: {
          type: "Polygon",
          coordinates: [[[92.13, 32.11], [108.72, 32.11], [108.72, 42.57], [92.13, 42.57], [92.13, 32.11]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "青海" },
        geometry: {
          type: "Polygon",
          coordinates: [[[89.35, 31.39], [103.04, 31.39], [103.04, 39.19], [89.35, 39.19], [89.35, 31.39]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "新疆" },
        geometry: {
          type: "Polygon",
          coordinates: [[[73.40, 34.25], [96.23, 34.25], [96.23, 49.11], [73.40, 49.11], [73.40, 34.25]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "西藏" },
        geometry: {
          type: "Polygon",
          coordinates: [[[78.25, 26.50], [99.06, 26.50], [99.06, 36.32], [78.25, 36.32], [78.25, 26.50]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "内蒙古" },
        geometry: {
          type: "Polygon",
          coordinates: [[[97.12, 37.24], [126.04, 37.24], [126.04, 53.23], [97.12, 53.23], [97.12, 37.24]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "宁夏" },
        geometry: {
          type: "Polygon",
          coordinates: [[[104.17, 35.14], [107.39, 35.14], [107.39, 39.23], [104.17, 39.23], [104.17, 35.14]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "黑龙江" },
        geometry: {
          type: "Polygon",
          coordinates: [[[121.11, 43.26], [135.09, 43.26], [135.09, 53.33], [121.11, 53.33], [121.11, 43.26]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "吉林" },
        geometry: {
          type: "Polygon",
          coordinates: [[[121.38, 40.52], [131.19, 40.52], [131.19, 46.75], [121.38, 46.75], [121.38, 40.52]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "辽宁" },
        geometry: {
          type: "Polygon",
          coordinates: [[[118.53, 38.43], [125.46, 38.43], [125.46, 43.26], [118.53, 43.26], [118.53, 38.43]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "北京" },
        geometry: {
          type: "Polygon",
          coordinates: [[[115.42, 39.44], [117.51, 39.44], [117.51, 41.06], [115.42, 41.06], [115.42, 39.44]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "天津" },
        geometry: {
          type: "Polygon",
          coordinates: [[[116.71, 38.34], [118.04, 38.34], [118.04, 40.25], [116.71, 40.25], [116.71, 38.34]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "上海" },
        geometry: {
          type: "Polygon",
          coordinates: [[[120.52, 30.40], [122.12, 30.40], [122.12, 31.53], [120.52, 31.53], [120.52, 30.40]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "海南" },
        geometry: {
          type: "Polygon",
          coordinates: [[[108.37, 18.01], [111.03, 18.01], [111.03, 20.10], [108.37, 20.10], [108.37, 18.01]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "台湾" },
        geometry: {
          type: "Polygon",
          coordinates: [[[119.28, 21.90], [122.01, 21.90], [122.01, 25.30], [119.28, 25.30], [119.28, 21.90]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "香港" },
        geometry: {
          type: "Polygon",
          coordinates: [[[113.76, 22.13], [114.41, 22.13], [114.41, 22.56], [113.76, 22.56], [113.76, 22.13]]]
        }
      },
      {
        type: "Feature",
        properties: { name: "澳门" },
        geometry: {
          type: "Polygon",
          coordinates: [[[113.52, 22.13], [113.60, 22.13], [113.60, 22.22], [113.52, 22.22], [113.52, 22.13]]]
        }
      }
    ]
  }
  
  // 注册备用地图
  echarts.registerMap('china', fallbackMapData)
  
  regionChartInstance = echarts.init(regionChart.value)
  
  // 获取数据的最大值和最小值，用于设置颜色范围
  const values = chinaRegionData.value.map(item => item.value)
  const maxValue = Math.max(...values)
  const minValue = Math.min(...values)
  
  const option = {
    title: {
      text: '🌍 用户地区分布',
      left: 'center',
      textStyle: {
        fontSize: 20,
        color: '#333',
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        if (params.value) {
          return `${params.name}<br/>用户数量：${params.value.toLocaleString()}人<br/>占比：${((params.value / chinaRegionData.value.reduce((sum, item) => sum + item.value, 0)) * 100).toFixed(2)}%`
        }
        return `${params.name}<br/>暂无数据`
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      extraCssText: 'box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);'
    },
    visualMap: {
      min: minValue,
      max: maxValue,
      left: 'left',
      top: 'bottom',
      text: [`高（${maxValue.toLocaleString()}）`, `低（${minValue.toLocaleString()}）`],
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      calculable: true,
      orient: 'horizontal',
      itemWidth: 20,
      itemHeight: 140,
      inRange: {
        // 使用从浅到深的蓝色渐变，用户数量多的省份颜色更深
        color: [
          '#f0f9ff',  // 最浅 - 用户数量最少
          '#e0f2fe',  
          '#bae6fd',  
          '#7dd3fc',  
          '#38bdf8',  
          '#0ea5e9',  
          '#0284c7',  
          '#0369a1',  
          '#075985',  
          '#0c4a6e'   // 最深 - 用户数量最多
        ]
      },
      outOfRange: {
        color: '#f5f5f5'
      },
      formatter: function(value) {
        return value.toLocaleString() + '人'
      }
    },
    series: [
      {
        name: '用户分布',
        type: 'map',
        map: 'china',
        roam: true,
        scaleLimit: {
          min: 1.0,
          max: 5
        },
        zoom: 1.1,
        itemStyle: {
          areaColor: '#f0f9ff',
          borderColor: '#ffffff',
          borderWidth: 1.5,
          shadowColor: 'rgba(0, 0, 0, 0.1)',
          shadowOffsetX: 1,
          shadowOffsetY: 1
        },
        emphasis: {
          itemStyle: {
            areaColor: '#ff6b6b',
            borderColor: '#ffffff',
            borderWidth: 2,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowBlur: 20,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: true,
            fontSize: 12,
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        select: {
          itemStyle: {
            areaColor: '#ffa500'
          }
        },
        label: {
          show: true,
          fontSize: 8,
          color: '#333333',
          fontWeight: 'normal'
        },
        data: chinaRegionData.value
      }
    ]
  }
  
  regionChartInstance.setOption(option)
  
  // 添加点击事件
  regionChartInstance.on('click', function(params) {
    console.log('点击了省份：', params.name, '用户数量：', params.value)
    ElMessage.info(`${params.name}：${params.value ? params.value.toLocaleString() : '暂无数据'}人`)
  })
}

// 生命周期
onMounted(() => {
  setTimeout(() => {
    initUserGrowthChart()
    initDetectionTypesChart()
    initActiveTimeChart()
    initRegionChart()
  }, 100)
})

onUnmounted(() => {
  if (userGrowthChartInstance) {
    userGrowthChartInstance.dispose()
  }
  if (detectionTypesChartInstance) {
    detectionTypesChartInstance.dispose()
  }
  if (activeTimeChartInstance) {
    activeTimeChartInstance.dispose()
  }
  if (regionChartInstance) {
    regionChartInstance.dispose()
  }
})
</script>

<style scoped>
.usage-statistics {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #7f8c8d;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.key-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.metric-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-left: 4px solid #409eff;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.metric-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.metric-trend {
  font-size: 14px;
  font-weight: bold;
}

.metric-trend.positive {
  color: #67c23a;
}

.metric-body {
  text-align: center;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.metric-label {
  color: #666;
  font-size: 14px;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-card h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 为地区分布图表增加更高的高度 */
.chart-card:nth-child(4) .chart-container {
  height: 600px; /* 与地区分布图表保持一致 */
}

.chart-card:nth-child(4) .chart {
  height: 100%;
}

.region-chart-section {
  grid-column: 1 / -1; /* 使其独占一行 */
  margin-bottom: 30px;
}

.region-chart-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.region-chart-container {
  height: 600px; /* 进一步增加地图高度 */
}

.detailed-stats {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.stats-table {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stats-table h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.feature-ranking {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.feature-ranking h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.ranking-number {
  width: 30px;
  height: 30px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
}

.ranking-info {
  flex: 1;
}

.feature-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.feature-usage {
  font-size: 12px;
  color: #666;
}

.ranking-percent {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .key-metrics {
    grid-template-columns: 1fr;
  }
  
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .detailed-stats {
    grid-template-columns: 1fr;
  }
}
</style> 